/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.io;

import org.dopdf.document.model.ResourceDetail;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The response writer.  The main job of this guy is to take the resource detail and write it to the response stream.
 *
 * @author Deep Shah
 */
public class ResponseWriter {

    /** The logger reference. */
    private static final Logger logger = Logger.getLogger(ResponseWriter.class.toString());

    /** The servlet response reference. */
    private ServletResponse response;

    /**
     * The constructor that takes the servlet response as argument.
     * @param response the response reference where we will eventually write our information.
     */
    public ResponseWriter(final ServletResponse response) {
        this.response = response;
    }

    /**
     * Writes the resource detail to the servlet output stream.
     * @param resourceDetail the resource detail that is to be written to the output stream.
     */
    public void write(final ResourceDetail resourceDetail) {
        try {
            final ServletOutputStream outputStream = response.getOutputStream();
            response.setContentLength(resourceDetail.getLength());
            response.setContentType(resourceDetail.getContentType());
            outputStream.write(resourceDetail.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (final Exception e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
        }

    }
}
